﻿using Jayden.Dll.Core.Persistence.Models;
using Jayden.Dll.Core.Persistence.Tools;

namespace Jayden.Dll.Core.Persistence.Data
{
	public class MSAccessDataAccess<T> : DbDataAccess<T> where T : Object
	{
		protected static readonly AccessHelper Helper = new AccessHelper();
		public MSAccessDataAccess(Configuration config, UnitOfWork uow, Entity entity) : base(config, uow, entity) { }

		protected override void AssignLastGeneratedObjectId(T obj)
		{
			using (DbCommandProxy lastInsertedIdCommand = CreateCommand("SELECT @@Identity"))
			{
				long rowid = (long)lastInsertedIdCommand.Command.ExecuteScalar();
				obj.ObjectId[0] = rowid;
			}
		}

		private string m_CreateCommandText;
		private string m_ReadCommandText;
		private string m_UpdateCommandText;
		private string m_DeleteCommandText;
		private string m_CreateTableCommandText;

		protected override string CreateCommandText
		{
			get
			{
				if (m_CreateCommandText == null)
					m_CreateCommandText = Helper.GenerateInsertInto(Entity);
				return m_CreateCommandText;
			}
		}

		protected override string ReadCommandText
		{
			get
			{
				if (m_ReadCommandText == null)
					m_ReadCommandText = Helper.GenerateSelect(Entity);
				return m_ReadCommandText;
			}
		}

		protected override string UpdateCommandText
		{
			get
			{
				if (m_UpdateCommandText == null)
					m_UpdateCommandText = Helper.GenerateUpdate(Entity);
				return m_UpdateCommandText;
			}
		}

		protected override string DeleteCommandText
		{
			get
			{
				if (m_DeleteCommandText == null)
					m_DeleteCommandText = Helper.GenerateDelete(Entity);
				return m_DeleteCommandText;
			}
		}

		protected override string CreateTableCommandText
		{
			get
			{
				if (m_CreateTableCommandText == null)
					m_CreateTableCommandText = Helper.GenerateCreateTable(Entity);
				return m_CreateTableCommandText;
			}
		}

		protected override string DropTableCommandText
		{
			get { return string.Format("DROP TABLE {0}", Entity.Table.TableName); }
		}
	}
}
